package cn.xmstore.interceptor;

import cn.xmstore.util.JWTUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author： Aeolia
 * @Description： TODO token验证拦截器
 * @Date： 2021/8/27 20:07
 **/
@Component
public class JWTInterceptor implements HandlerInterceptor {


    @Override

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("拦截器拦截");
        String token = request.getHeader("token");
        if (token != null && token != "") {
            //验证token
            switch (JWTUtil.verify(token)) {
                //验证token超时，是否可刷新，可刷新则刷新token，不可刷新则重新登录
                case 200://未超时
                    System.out.println("存在token信息，验证通过");
                    return true;
                case 201://超时可刷新
                    System.out.println("存在token信息但已超时，可刷新，进行token刷新");
                    //进行token刷新
                    Map<String, Object> info = JWTUtil.getInfo(token);
                    if (info != null) {
                        int id = (Integer) info.get("id");
                        String name = (String) info.get("name");
                        String newToken = JWTUtil.generateToken(id, name);
                        response.setHeader("token",newToken);
                        System.out.println("token刷新成功");
                        return true;
                    }
                        System.out.println("token刷新失败");
                    return false;
                case 300,301://300验证失败和301超时不可刷新
                    System.out.println("存在token信息验证失败或已超时");
                    return false;
                default:
                    return false;
            }
        } else {
            System.out.println("没有token信息，转发到登录页");
            request.getRequestDispatcher("/user/login").forward(request, response);
            return false;
        }
    }
}
